﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;
using UploadManager;
using UnityCore;

using System.Drawing.Printing;

namespace MBBStoreClient
{
    public partial class frmChargedInvoiceViewer : Form
    {

        SynchronizeData sync = new SynchronizeData();
        UnityScriptEngine.Threader t = new UnityScriptEngine.Threader();
        float gtotal = 0f,ptotal = 0f, bal = 0f;
        readDetails path = new readDetails();
        readDetails pLD = new readDetails();
        priceDetails pD = new priceDetails();

        DataTable exportChargeInvoice = new DataTable();
        DataTable exportChargeInvoiceItem = new DataTable();
        DataTable exportChargePayment = new DataTable();
        DataTable exportChargeBalance = new DataTable();

        DataTable extractedPO = new DataTable();

        string curPO = "", curStoreName;
        bool isViewing = false;
        DataTable items = new DataTable();
        DataTable supplier = new DataTable();
        DataTable prods = new DataTable();

        public frmChargedInvoiceViewer(string PONumber, string StoreName)
        {
            curPO = PONumber;
            curStoreName = StoreName;

            path.fileNames = new List<string>();
            pD.tables = new List<DataTable>();
            isViewing = true;
            InitializeComponent();
            InitializeFrameSliderForm();
            btnPrint.Click += new EventHandler(btnPrint_Click);
        }

        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintPO();
        }
        public frmChargedInvoiceViewer()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            sync.ProcessCompleted += new CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new CoreHandler(sync_ProcessError);
            sync.Stores();
            
            States(false);
            InitializeItemTable();
        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
               // pnlMsg.Visible = false;
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        //extract data
                        path.date = "";
                        path.remNode = curStoreName;
                        path.fileNames.Clear();
                        path.fileNames.Add("Charge Invoice");
                        path.fileNames.Add("Charge Invoice Item");
                        path.fileNames.Add("Charge Payments");
                        path.fileNames.Add("Charge Balance");
                        sync.ReadMany(path);
                        break;
                    case "ReadMany":
                        exportChargeInvoice = sync.exportTables[0];
                        exportChargeInvoiceItem = sync.exportTables[1];
                        exportChargePayment = sync.exportTables[2];
                        exportChargeBalance = sync.exportTables[3];
                            
                        CreateDataTable();
                        grdItems.DataSource = items;
                        break;
                }
            });
        }

        void CreateDataTable()
        {
            for (int i = 0; i < exportChargeInvoiceItem.Rows.Count; i++)
            {
                if (curPO.Equals(exportChargeInvoiceItem.Rows[i]["fInvoice"].ToString()))
                {
                    DataRow dr = items.NewRow();
                    dr[1] = exportChargeInvoiceItem.Rows[i]["fDescription"].ToString();
                    dr[2] = exportChargeInvoiceItem.Rows[i]["fQty"].ToString();
                    dr[3] = exportChargeInvoiceItem.Rows[i]["fUnit"].ToString();
                    dr[4] = exportChargeInvoiceItem.Rows[i]["fUnitPrice"].ToString();
                    items.Rows.Add(dr);
                }
            }

            for (int i = 0; i < exportChargeInvoice.Rows.Count; i++)
            {
                if (curPO.Equals(exportChargeInvoice.Rows[i]["fInvoice"].ToString()))
                {
                    txtChargeInvoice.Text = curPO;
                    txtAccountName.Text = exportChargeInvoice.Rows[i]["fSoldTo"].ToString();
                    txtRefNum.Text = exportChargeInvoice.Rows[i]["fRef"].ToString();
                    txtDate.Text = exportChargeInvoice.Rows[i]["fDate"].ToString();
                    txtAddress.Text = exportChargeInvoice.Rows[i]["fAddress"].ToString();

                    break;
                }
            }
            for (int i = 0; i < exportChargeBalance.Rows.Count; i++)
            {
                if (txtChargeInvoice.Text.Equals(exportChargeBalance.Rows[i]["fInvoice"].ToString()))
                {
                    txtTerms.Text = exportChargeBalance.Rows[i]["fTerms"].ToString();
                    break;
                }
            }
            

            gtotal = 0;
            for (int i = 0; i < items.Rows.Count; i++)
            {
                gtotal += (float)items.Rows[i]["SubTotal"];
            }
            txtTotal.Text = gtotal.ToString("#,#0.00");


            
            DataRow[] arr = exportChargePayment.Select("fInvoiceNumber = '" + txtChargeInvoice.Text + "'");
            DataTable pay = new DataTable();
            pay.Columns.Add("Date", typeof(DateTime));
            pay.Columns.Add("Official Receipt", typeof(string));
            pay.Columns.Add("PaymentAmt", typeof(string));
            pay.Columns.Add("Type", typeof(string));
            pay.Columns.Add("BankName", typeof(string));
            pay.Columns.Add("Check Number", typeof(string));
            pay.Columns.Add("DueDate", typeof(DateTime));

            for (int i = 0; i < arr.Length; i++)
            {
                DataRow dr = pay.NewRow();
                dr[0] = DateTime.Parse(arr[i]["fDateReceived"].ToString());
                dr[1] = arr[i]["fORNumber"].ToString();
                dr["PaymentAmt"] = Common.FormatCurrency(float.Parse(arr[i]["fAmount"].ToString()));
                dr["Type"] = arr[i]["fPaymentMode"].ToString();
                dr["BankName"] = arr[i]["fBankName"].ToString();
                dr["Check Number"] = arr[i]["fCheckNumber"].ToString();
                
                string dDate="";
            
                if (arr[i]["fDueDate"].ToString().Equals(""))
                {
                    dDate = "";
                }
                else
                {
                    dDate = arr[i]["fDueDate"].ToString();
                    dr["DueDate"] = DateTime.Parse(dDate);
                }

                pay.Rows.Add(dr);
                ptotal += float.Parse(pay.Rows[i]["PaymentAmt"].ToString());
            }

            txtTotalPayment.Text = ptotal.ToString("#,#0.00");
            grdPayments.DataSource = pay;
            grdPayments.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            bal = gtotal - ptotal;
            txtBalance.Text = bal.ToString("#,#0.00");
            if (bal > 0)
            {
                txtBalance.ForeColor = Color.Red;
            }
            else
            {
                txtBalance.ForeColor = Color.Black;
            }
            
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
        }

        void InitializeItemTable()
        {
            items.Columns.Add("Num");
            items.Columns.Add("Description");
            items.Columns.Add("Qty");
            items.Columns.Add("Unit");
            items.Columns.Add("Price");
            items.Columns.Add("SubTotal");

            items.Columns[0].AutoIncrementSeed = 1;
            items.Columns[0].AutoIncrement = true;
            items.Columns[0].DataType = typeof(int);

            items.Columns[2].DataType = typeof(float);
            items.Columns[2].DefaultValue = 0.00f;
            items.Columns[4].DataType = typeof(float);
            items.Columns[4].DefaultValue = 0.00f;

            items.Columns[5].DataType = typeof(float);
            items.Columns[5].Expression = "[Qty] * [Price]";

            grdItems.DataSource = items;
            //grdItems.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grdItems.Columns[2].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[4].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[5].DefaultCellStyle.Format = "#,#0.00";

            grdItems.Columns[0].Width = (grdItems.Width * 7) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 37) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 15) / 100;
            grdItems.Columns[3].Width = (grdItems.Width * 7) / 100;
            grdItems.Columns[4].Width = (grdItems.Width * 15) / 100;
            grdItems.Columns[5].Width = (grdItems.Width * 15) / 100;
            
        }

        void PrintPO()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }
        }
        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 50;
            float lw = e.PageBounds.Width - 50;
            float th = e.PageBounds.Height - 100;
            float tHt = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            //Title
            cFont = new Font("Arial", 16f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("MBB ROYALE INT'L INC.", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("MacArthur Hi-way, Guinhawa, Malolos Bulacan", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Telephone Number: (044) 791-03-78 , (044) 662-40-79", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            //e.Graphics.DrawString("Fax Number: (044) 662-37-62", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //Line
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            e.Graphics.DrawString("CHARGE INVOICE FORM", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            y += tHt;
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));
            //SUPPLIER Line
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("REFERENCE NO: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            e.Graphics.DrawString("Charge Invoice #: " + txtChargeInvoice.Text, cFont, Brushes.Black, lw - 280, y, new StringFormat());

            cFont = new Font("Arial", 12f, FontStyle.Italic);
            e.Graphics.DrawString("" + txtRefNum.Text, cFont, Brushes.Black, lm + 180, y, new StringFormat());

            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(500, y));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(760, y), new PointF(600, y));
            //SUPPLIER Line
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("ACCOUNT NAME: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            e.Graphics.DrawString("DATE: ", cFont, Brushes.Black, lw - 280, y, new StringFormat());

            cFont = new Font("Arial", 12f, FontStyle.Italic);
            e.Graphics.DrawString("" + txtAccountName.Text, cFont, Brushes.Black, lm + 180, y, new StringFormat());
            e.Graphics.DrawString("" + txtDate.Text, cFont, Brushes.Black, 600, y, new StringFormat());

            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(500, y));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(760, y), new PointF(600, y));
            //ADDRESS Line

            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("ADDRESS: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            cFont = new Font("Arial", 12f, FontStyle.Italic);
            e.Graphics.DrawString("" + txtAddress.Text, cFont, Brushes.Black, lm + 180, y, new StringFormat());

            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(760, y));

            y += tHt;
            //Table Columns
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            y += tHt;
            e.Graphics.DrawString("No.", cFont, Brushes.Black, lm + 4, y, new StringFormat());
            e.Graphics.DrawString("Description", cFont, Brushes.Black, lm + 40, y, new StringFormat());
            e.Graphics.DrawString("Qty", cFont, Brushes.Black, lm + 405, y, new StringFormat());
            e.Graphics.DrawString("Price", cFont, Brushes.Black, lm + 565, y, new StringFormat());
            e.Graphics.DrawString("Sub Total", cFont, Brushes.Black, lm + 660, y, new StringFormat());

            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lw, y - (tHt / 2)));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 35, y - (tHt / 2)), new PointF(lm + 35, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 400, y - (tHt / 2)), new PointF(lm + 400, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 560, y - (tHt / 2)), new PointF(lm + 560, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 655, y - (tHt / 2)), new PointF(lm + 655, y + tHt));

            //Table
            y += (tHt * 1.25f);
            cFont = new Font("Arial Narrow", 10f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            bool nf = false;
            for (int i = 0; i < 30; i++)
            {
                e.Graphics.DrawString((i + 1) + "", cFont, Brushes.Black, lm + 4, y, new StringFormat());
                if (grdItems.Rows.Count > i)
                {
                    sf.Alignment = StringAlignment.Near;        
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[1].Value.ToString(), cFont, Brushes.Black, lm + 40, y, sf);
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[2].Value.ToString() + " " + grdItems.Rows[i].Cells[3].Value.ToString(), cFont, Brushes.Black, lm + 405, y, sf);
                    sf.Alignment = StringAlignment.Far;
                    e.Graphics.DrawString("" + Common.FormatCurrency(grdItems.Rows[i].Cells[4].Value.ToString()), cFont, Brushes.Black, lm + 656, y, sf);
                    e.Graphics.DrawString("" + Common.FormatCurrency(grdItems.Rows[i].Cells[5].Value.ToString()), cFont, Brushes.Black, lm + 750, y, sf);
                }
                else
                {
                    if (!nf)
                    {
                        //Nothing Follows
                        e.Graphics.DrawString("" + Common.FormatCurrency(txtTotal.Text), cFont, Brushes.Black, lm + 750, y, sf);
                        e.Graphics.DrawString("******************** Nothing Follows ********************", cFont, Brushes.Black, lm + 300, y, new StringFormat());
                        nf = true;
                    }
                }
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 35, y - (tHt / 2)), new PointF(lm + 35, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 400, y - (tHt / 2)), new PointF(lm + 400, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 560, y - (tHt / 2)), new PointF(lm + 560, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 655, y - (tHt / 2)), new PointF(lm + 655, y + tHt));

                y += (tHt * 1.25f);

            }

            //STORE Line
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("NUMBER OF ITEMS: " + grdItems.Rows.Count, cFont, Brushes.Black, lm + 20, y, new StringFormat());
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("SHIP TO: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            cFont = new Font("Arial", 11f, FontStyle.Italic);
            e.Graphics.DrawString(""  , cFont, Brushes.Black, lm + 180, y, new StringFormat());
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(500, y));
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            e.Graphics.DrawString("ADDRESS: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            cFont = new Font("Arial", 11f, FontStyle.Italic);
            e.Graphics.DrawString("" , cFont, Brushes.Black, lm + 180, y, new StringFormat());
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(760, y));

            y += tHt;
            e.Graphics.DrawString("_____________________________", cFont, Brushes.Black, lw - 190, y, sf);

            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("AUTHORIZED SIGNATURE", cFont, Brushes.Black, lw - 190, y, sf);

        }
    }
}